using System.Collections.Generic;
using SimpleJSON;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Gj
{
    public class ChatListHelper : NodeHelper, IEndDragHandler
    {
        public GameObject other;
        public GameObject self;
        public GameObject content;
        public GameObject empty;
        public RectTransform rect;
        public bool refresh;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey selfKey;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey channelKey;
        public int offsetHeight;
        private string _channel;
        private float _currentHeight;
        private float _currentWidth;
        private float _height;
        private ScrollRect _ScrollRect;
        private bool _update;
        private float _width;

        private readonly List<ChatItemHelper> list = new();

        protected override BindDataType bindDataType => BindDataType.All;

        private ScrollRect ScrollRect
        {
            get
            {
                if (_ScrollRect == null) _ScrollRect = GetComponent<ScrollRect>();
                return _ScrollRect;
            }
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            if (refresh)
            {
                var v = ScrollRect.verticalNormalizedPosition;
                if (v < 0) Emit(UIEvent.PullUp);
                if (v > 1) Emit(UIEvent.PullDown);
            }
        }

        protected override void Init()
        {
            base.Init();
            if (content == null) content = gameObject;
        }

        protected override void BindData(JSONObject json)
        {
            var channel = channelKey.Get(json).Value;
            if (channel != _channel) _update = true;
            _channel = channel;
            JSONNode data = dataKey.Get(json).AsObject;
            if (_update)
            {
                for (var i = 0; i < list.Count; i++) Destroy(list[i].gameObject);
                list.Clear();
                _update = false;
            }

            if (channel == null || data[channel] == null)
            {
                BindData(new JSONArray());
            }
            else
            {
                Debug.LogErrorFormat("{0} {1} {2}", _update, channel, data[channel]);
                BindData(data[channel].AsArray);
            }
        }

        protected override void BindData(JSONArray array)
        {
            var _width = rect.rect.width;

            var s = 0;
            for (var i = list.Count; i < array.Count; i++)
            {
                var obj = array[i] == null ? new JSONObject() : array[i].AsObject;
                var isSelf = selfKey.Get(obj).AsBool;
                var item = ModelTools.Create(isSelf ? self : other, content).GetComponent<ChatItemHelper>();
                item.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, _width);
                list.Add(item);
                BindEvent(item);
                item.SetData(obj);
                item.Show();
                s++;
            }

            if (list.Count == 0)
            {
                if (empty != null) empty.SetActive(true);
            }
            else
            {
                if (empty != null) empty.SetActive(false);
            }


            var group = content.GetComponent<VerticalLayoutGroup>();
            var height = GetHeight();
            height += (list.Count - 1) * group.spacing;
            height += group.padding.top;
            height += group.padding.bottom;

            rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
            if (height > offsetHeight) rect.anchoredPosition = new Vector2(0, height - offsetHeight);
        }

        private float GetHeight()
        {
            float h = 0;
            for (var i = 0; i < list.Count; i++) h += list[i].GetComponent<ChatItemHelper>().GetHeight();

            return h;
        }

        private void SetHeight(float height)
        {
        }
    }
}